//
//  ViewController.m
//  WholeMusic
//
//  Created by quanxiong on 2018/2/11.
//  Copyright © 2018年 quanxiong. All rights reserved.
//

#import "WMMusicSearchResultsVC.h"
#import "WMApiService.h"
#import "WMMusic.h"
#import "WMDownloadManager.h"
#import "WMUtils.h"
#import "WMMusicVCBase+Player.h"

#import <YYKit/YYKit.h>

#import "WMMusicApiQQ.h"
#import "WMMusicApiNetease.h"

@interface WMMusicSearchResultsVC () <UISearchBarDelegate>

@property (strong, nonatomic) NSArray<WMMusic *> *musicList;

@property (strong, nonatomic) WMMusicApiQQ *qqApi;
@property (strong, nonatomic) WMMusicApiNetease *neteaseApi;

@end

@implementation WMMusicSearchResultsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"找音乐";
    
    //test code
    _qqApi = [[WMMusicApiQQ alloc] init];
    _neteaseApi = [[WMMusicApiNetease alloc] init];
    
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.delegate = self;
    searchBar.placeholder = @"搜索歌曲(支持 QQ、网易)";
    searchBar.searchBarStyle = UISearchBarStyleMinimal;
    [searchBar sizeToFit];
    self.tableView.tableHeaderView = searchBar;
    
    searchBar.text = @"刘德华";
    [self searchMusic:searchBar.text];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - UISearchBarDelegate
- (void)searchMusic:(NSString *)keyword {
    if (keyword.length == 0) {
        return;
    }
    @weakify(self);
    [_neteaseApi searchMusicAsync:keyword page:0 complete:^(NSArray *musicList) {
        @strongify(self);
        self.musicList = [musicList copy];
        [self.tableView reloadData];
    }];
//    [_qqApi searchMusicAsync:keyword page:0 complete:^(NSArray<WMMusic *> *musicList) {
//        @strongify(self);
//        self.musicList = [musicList copy];
//        [self.tableView reloadData];
//    }];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.view endEditing:YES];
    [self searchMusic:searchBar.text];
}

- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar {
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
}

#pragma mark - tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.musicList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MusicCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MusicCell"];
    }
    WMMusic *music = self.musicList[indexPath.row];
    __block WMMusic *dbMusic;
    fp_dispatch_global_then_dispatch_main_queue(^{
        dbMusic = [WMMusic queryWithMusic:music];
    }, ^{
        CGFloat fileSize = [dbMusic fileSize];
        if (fileSize > 0.1 && [cell.textLabel.text isEqualToString:dbMusic.songname]) {
            cell.textLabel.text =
            [NSString stringWithFormat:@"%@[下载完成[%.2fMB]]", dbMusic.songname, fileSize];
        }
    });
    cell.textLabel.text = music.songname;
    cell.detailTextLabel.text =
    [NSString stringWithFormat:@"%@<%@>", music.singer.firstObject.name, music.albumname];
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

#pragma mark - 左滑菜单
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    @weakify(self);
    UITableViewRowAction *favorite =
    [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal
                                       title:@"收藏"
                                     handler:
     ^(UITableViewRowAction *action, NSIndexPath *indexPath) {
         @strongify(self);
         WMMusic *music = self.musicList[indexPath.row];
         music.favorite = @"最爱";
         [music xq_save];
         // 收回左滑出现的按钮(退出编辑模式)
         tableView.editing = NO;
     }];
    favorite.backgroundColor = UIColorHex(ed81dc);
    
    UITableViewRowAction *album =
    [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal
                                       title:@"专辑"
                                     handler:
     ^(UITableViewRowAction *action, NSIndexPath *indexPath) {
         @strongify(self);
         // 收回左滑出现的按钮(退出编辑模式)
         tableView.editing = NO;
     }];
    album.backgroundColor = UIColorHex(717af7);
    
    //播放
    UITableViewRowAction *play =
    [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal
                                       title:@"播放"
                                     handler:
     ^(UITableViewRowAction *action, NSIndexPath *indexPath) {
         @strongify(self);
         // 收回左滑出现的按钮(退出编辑模式)
         tableView.editing = NO;
         [self fetchMusicFileWithIndexPath:indexPath complete:^(WMMusic *music) {
             @strongify(self);
             [self startPlay:music];
         } needDownload:NO];
     }];
    play.backgroundColor = UIColorHex(717af7);
    
    
    UITableViewRowAction *download =
    [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal
                                       title:@"下载"
                                     handler:
     ^(UITableViewRowAction *action, NSIndexPath *indexPath) {
         @strongify(self);
         // 收回左滑出现的按钮(退出编辑模式)
         tableView.editing = NO;
         [self fetchMusicFileWithIndexPath:indexPath complete:nil needDownload:YES];
     }];
    download.backgroundColor = UIColorHex(4fb9f8);
    
    return @[download, play, favorite, album];
}

- (void)fetchMusicFileWithIndexPath:(NSIndexPath *)indexPath
                           complete:(void(^)(WMMusic *music))complete
                       needDownload:(BOOL)needDownload {
    @weakify(self);
    WMMusic *music = self.musicList[indexPath.row];
    WMMusic *dbMusic = [WMMusic queryWithMusic:music];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[dbMusic filePath]];
    if (fileExists) {
        if (complete) {
            complete(dbMusic);
            return;
        }
    }
    if (music.musicUrl.length > 0) {
        @strongify(self);
        if (needDownload) {
            [self startDownloadMusic:music indexPath:indexPath complete:complete];
        } else {
            if (complete) {
                complete(music);
            }
        }
    } else {
        [self.qqApi getMusicLinkByMusic:music complete:^(NSString *musicUrl) {
            @strongify(self);
            music.musicUrl = musicUrl;
            if (needDownload) {
                [self startDownloadMusic:music indexPath:indexPath complete:complete];
            } else {
                if (complete) {
                    complete(music);
                }
            }
        }];
    }
}

- (void)startDownloadMusic:(WMMusic *)music indexPath:(NSIndexPath *)indexPath complete:(void(^)(WMMusic *music))complete {
    NSLog(@"开始下载:%@", music.musicUrl);
    music.status = WMMusicStatusDownloading;
    music.fileName = [music defaultFileName];
    [music xq_save];
    NSString *filePath = [music defaultFilePath];
    
    [[WMDownloadManager sharedManager] addDownloadTaskWithUrl:music.musicUrl
                                                     filePath:filePath
                                                     progress:
     ^(NSProgress *downloadProgress) {
         fp_dispatch_main_sync_safe(^{
             CGFloat progress = 100. * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
             UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
             cell.textLabel.text = [NSString stringWithFormat:@"%@[下载中 %.0f%%]", music.songname, progress];
         });
     } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
         fp_dispatch_main_sync_safe(^{
             NSString *path = filePath.path;
             if (!filePath) {
                 path = [music filePath];
             }
             music.status = WMMusicStatusDownloaded;
             [music xq_save];
             
             UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
             cell.textLabel.text =
             [NSString stringWithFormat:@"%@[下载完成[%.2fMB]]", music.songname, [music fileSize]];
             if (complete) {
                 complete(music);
             }
         });
     }];
}

@end
